'use strict';
const db = uniCloud.database();
var ip = '';
var _appId = ''
var _wxPayKey = ''
var _wxPayMchId = ''
var isMiniApp = ''
const NodeRSA = require('node-rsa') // 需要执行npm install node-rsa才能调用
const querystring = require('querystring') // node自带，无需安装，直接调用
module.exports = {
	/**
	 * 此函数名称
	 * @url user/pub/test1 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			out_trade_no,
			trade_no
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		const appIds = await db.collection('wx_config').where({
			'key': 'zfbId'
		}).get()
		const wxPayKey = await db.collection('wx_config').where({
			'key': 'zfbPrivateKey'
		}).get()
		const wxPayMchId = await db.collection('wx_config').where({
			'key': 'zfbBlipayPublicKey'
		}).get()
		_appId = appIds.data[0].val
		_wxPayKey = wxPayKey.data[0].val
		_wxPayMchId = wxPayMchId.data[0].val
		// 业务逻辑开始-----------------------------------------------------------
		// 可写与数据库的交互逻辑等等
		const AlipaySdk = require('alipay-sdk').default;
		const AlipayFormData = require('alipay-sdk/lib/form').default
		// TypeScript，可以使用 import AlipaySdk from 'alipay-sdk';
		// 普通公钥模式
		const alipaySdk = new AlipaySdk({
			gateway: "https://openapi.alipay.com/gateway.do",
			appId: _appId,
			// 应用私钥
			privateKey: _wxPayKey,
			// 支付宝公钥
			alipayPublicKey: _wxPayMchId,
		});
		// H5 支付接口，生成请求字符串
		const formData = new AlipayFormData()
		formData.setMethod("get")
		formData.addField("bizContent", {
			out_trade_no,
			trade_no
		})
		const zfbQueryOrderURL = await alipaySdk.exec("alipay.trade.query", {}, {
			formData: formData,
			// validateSign: true
		})

		const resData = await uniCloud.httpclient.request(zfbQueryOrderURL, {
			timeout: 90000,
			method: "get",
			contentType: 'json',
			dataType: "json"
		})
		let r = resData.data.alipay_trade_query_response
		let roderInfo = await vk.baseDao.findByWhereJson({
			dbName: "wx_order",
			whereJson: {
				order_id: out_trade_no,
			}
		});
		if (!roderInfo) {
			return {
				code: 0,
				type: "",
				msg: "没有订单id"
			}
		}
		console.log(roderInfo, '1111111111')
		if (r.code === "10000") {
			switch (r.trade_status) {
				case "WAIT_BUYER_PAY":
					return {
						code: 0,
							type: "WAIT_BUYER_PAY",
							msg: "支付宝有交易记录，没付款"
					}
					break;
				case "TRADE_FINISHED":
					return {
						code: 0,
							type: "TRADE_FINISHED",
							msg: "支付成功，不可以退款"
					}
					break;
				case "TRADE_SUCCESS":
					if (roderInfo.status == 1) {
						return {
							code: 0,
							type: "TRADE_SPACED",
							msg: "已经支付完了"
						}
					}
				
					return {
						code: 0,
							data: roderInfo,
							type: "TRADE_SUCCESS",
							msg: "支付成功"
					}
					break;
				case "TRADE_CLOSED":
					return {
						code: 0,
							type: "TRADE_CLOSED",
							msg: "交易关闭"
					}
					break;
				default:
					break;
			}
		} else if (r.code === "40004") {
			return {
				code: 10002,
				msg: "订单不存在"
			}
		} else {
			return {
				code: 10002,
				msg: "支付失败"
			}
		}
		// App 支付接口，生成请求字符串，
		// const orderStr1 = alipaySdk.sdkExec('alipay.trade.app.pay', {
		// 	bizContent: {
		// 		out_trade_no:  new Date().valueOf(),
		// 		product_code: "FAST_INSTANT_TRADE_PAY",
		// 		subject: data.title || '名称',
		// 		body: data.title || '名称',
		// 		total_amount: data.money
		// 	},
		// 	returnUrl: 'https://www.taobao.com'
		// })

		res.data = {}
		// 业务逻辑结束-----------------------------------------------------------
		return res;

	}
}


/* 商户订单编号*/
function getWxPayOrdrID() {
	var myDate = new Date();
	var year = myDate.getFullYear();
	var mouth = myDate.getMonth() + 1;
	var day = myDate.getDate();
	var hour = myDate.getHours();
	var minute = myDate.getMinutes();
	var second = myDate.getSeconds();
	var msecond = myDate.getMilliseconds(); //获取当前毫秒数(0-999)
	if (mouth < 10) {
		/*月份小于10  就在前面加个0*/
		mouth = String(String(0) + String(mouth));
	}
	if (day < 10) {
		/*日期小于10  就在前面加个0*/
		day = String(String(0) + String(day));
	}
	if (hour < 10) {
		/*时小于10  就在前面加个0*/
		hour = String(String(0) + String(hour));
	}
	if (minute < 10) {
		/*分小于10  就在前面加个0*/
		minute = String(String(0) + String(minute));
	}
	if (second < 10) {
		/*秒小于10  就在前面加个0*/
		second = String(String(0) + String(second));
	}
	if (msecond < 10) {
		msecond = String(String(0) + String(second));
	} else if (msecond >= 10 && msecond < 100) {
		msecond = String(String(0) + String(second));
	}

	var currentDate =
		String(year) +
		String(mouth) +
		String(day) +
		String(hour) +
		String(minute) +
		String(second) +
		String(msecond);
	return 'ai_zfb_' + currentDate;
}